import React, { useState, useRef, forwardRef, useImperativeHandle, useEffect } from 'react';
import { Divider, Button, Popconfirm, FormInstance, message } from 'antd';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { PlusOutlined, PauseCircleOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import { 
  getPlanProjectList, 
  addPlanProject,
  updatePlanProject,
  updatePlanProjectStatus,
  batchStopPlanProject } from '@/services/order/api';
import { showMsg, MsgType, formatDate, isSupportSticky, isScroll } from '@/utils/utils';
import { OptType, PlanOrderStatus } from '@/utils/constants';
import { useModel } from 'umi';
import AddProjectPlan from './AddProjectPlan';
import PermissionControl from '@/components/PermissionControl';
import ProForm, { ModalForm, ProFormDateTimePicker } from '@ant-design/pro-form';
import moment from 'moment';

type ProjectPlanItem = {
  project_id?: string;
  row_num?: number;
  brand_name?: string;
  goods_name?: string;
  goods_id?: string;
  goods_price?: number;
  specs_name?: string;
  unit?: string;
  frequency_id?: string;
  frequency_name?: string;
  frequency_desc?: string;
  is_first?: string;
  is_long?: string;
  use_num?: number;
  begin_time?: string;
  end_time?: string;
  remarks?: string;
  create_user_name?: string;
  plan_status?: string;
}

type ProjectPlanItemList = {
  record_list: ProjectPlanItem[];
  sum_record_num?: number;
}

interface ProjectPlanProps {
  order_id?: string;
  patientHospitalInfo?: ORDERAPI.PatientHospitalInfo,
  startProject?: (flag: boolean) => void;
  stopProject?: () => void;
  detail?: any;
  hasPlan: boolean;
  ref?: any;
  dischargeStatus?: string;
}

const ProjectPlan: React.FC<ProjectPlanProps> = forwardRef((props, ref) => {
  const { 
    order_id, 
    patientHospitalInfo, 
    startProject,
    stopProject,
    detail,
    dischargeStatus,
    hasPlan
   } = props;

  const { initialState } = useModel('@@initialState');
  // 启用
  const [enableLoading, setEnableLoading] = useState<boolean>(false);
  const [enableVisible, setEnableVisible] = useState<boolean>(false);

  // 删除
  const [deleteLoading, setDeleteLoading] = useState<boolean>(false);
  const [deleteVisible, setDeleteVisible] = useState<boolean>(false);

  // 停止
  const [stopLoading, setStopLoading] = useState<boolean>(false);
  const [stopVisible, setStopVisible] = useState<boolean>(false);

  const [line, setLine] = useState<number>(-1);

  const actionRef = useRef<ActionType>();

  const formRef = useRef<FormInstance>();

  const [clickRow, setClickRow] = useState(''); // 当前选中的行编号，用于定位颜色

  const [addProjectPlanDialog, setAddProjectPlanDialog] = useState<boolean>(false);
  const [currentRow, setCurrentRow] = useState<ProjectPlanItem>({});

  // 选择的ID
  const [selectIds, setSelectIds] = useState<string[]>([]);
  const [selectRows, setSelectRows] = useState<string[]>([]);

  const [optType, setOptType] = useState<string>(OptType.ADD);

  const [newCreateOrderId, setNewCreateOrderId] = useState<string>(order_id as string);

  const columns: ProColumns<ProjectPlanItem>[] = [
    {
      title: '编号',
      dataIndex: 'row_num',
      width: 35
    },
    {
      title: '品牌',
      dataIndex: 'brand_name',
      width: 70
    },
    {
      title: '商品名称',
      dataIndex: 'goods_name',
      width: 70
    },
    {
      title: '商品编号',
      dataIndex: 'goods_id',
      className: 'wordbreak',
      width: 65
    },
    {
      title: '规格(单位)',
      dataIndex: 'unit',
      width: 80,
      render: (_, entity) => {
        return `${entity.specs_name}(${entity.unit})`
      }
    },
    {
      title: '单价',
      dataIndex: 'goods_price',
      valueType: 'money',
      align: 'right',
      width: 60
    },
    {
      title: '执行频次',
      dataIndex: 'frequency_name',
      width: 85
    },
    {
      title: '单次用量',
      dataIndex: 'use_num',
      align: 'right',
      width: 55
    },
    {
      title: '包含首次消耗用量',
      dataIndex: 'is_first',
      align: 'right',
      width: 55
    },
    {
      title: '开始时间',
      dataIndex: 'begin_time',
      width: 80
    },
    {
      title: '结束时间',
      dataIndex: 'end_time',
      width: 80,
      render: (dom, entity) => {
        return entity.end_time || '长期'
      }
    },
    
    {
      title: '备注',
      dataIndex: 'remarks',
      className: 'wordbreak',
      width: 60
    },
    {
      title: '计划创建人',
      dataIndex: 'create_user_name',
      width: 65
    },
    {
      title: '状态',
      dataIndex: 'plan_status',
      width: 43,
      render: (_, record: ProjectPlanItem) => {
        return PlanOrderStatus[record.plan_status as string];
      }
    },
    {
      title: '操作',
      // fixed: 'right',
      fixed: isSupportSticky() && isScroll ? 'right' : '',
      width: 150,
      align: 'center',
      valueType: 'option',
      render: (_, record, index) => {
        // 计划状态C：已创建，R：执行中，S：已停止 
        const { plan_status } = record;
        // 已停止
        if (plan_status === 'S') {
          return [];
        }

        if (['W', 'F'].includes(dischargeStatus as string)) {
          return [];
        }

        // C：已创建
        if (plan_status === 'C') {
          return [
            <PermissionControl key="copy" action_id="400401021">
              <a onClick={() => {
                setAddProjectPlanDialog(true);
                setCurrentRow(record);
                setOptType(OptType.EDIT);
              }}>编辑</a>
            </PermissionControl>,
            <PermissionControl key="enable" action_id="400401008">
                <Popconfirm 
                  visible={enableVisible && line === index}
                  okButtonProps={{ loading: enableLoading }}
                  onConfirm={async () => {
                    const params = {
                      order_id: newCreateOrderId,
                      project_id: record.project_id as string,
                      plan_status: 'R',
                      begin_time: formatDate(record.begin_time as string),
                      end_time: record.end_time ? formatDate(record.end_time) : null
                    }
                    if (Number(record.is_long) === 1) {
                      delete params.end_time;
                    }
                    setEnableLoading(true);
                    const success = await modifyPlanProjectStatus(params);
                    setEnableVisible(false);
                    setEnableLoading(false);
                    setLine(-1);
                    if (success) {
                      showMsg('计划已启用', MsgType.SUCCESS);
                      actionRef.current?.reload();
                      startProject?.(true);
                    }
                  }}
                  onCancel={() => {
                    setEnableVisible(false)
                  }}
                  okText="确认开启" 
                  cancelText="再想想" 
                  placement="topRight"
                  title="计划启用后将按照设定开始时间进行计费，是否启用？">
                  <a onClick={() => {
                    setEnableVisible(true);
                    setLine(index);
                  }}>启用</a>
              </Popconfirm>
            </PermissionControl>,
            
            <PermissionControl key="delete"  action_id="400401010">
              <Popconfirm 
                visible={deleteVisible && line === index}
                okButtonProps={{loading: deleteLoading}}
                onConfirm={async () => {
                  setDeleteLoading(true);
                  const success = await modifyPlanProjectStatus({
                    order_id: newCreateOrderId,
                    project_id: record.project_id as string,
                    plan_status: 'D'
                  });
                  setDeleteLoading(false);
                  setDeleteVisible(false);
                  setLine(-1);
                  if (success) {
                    showMsg('计划已删除', MsgType.SUCCESS);
                    actionRef.current?.reload();
                  }
                }}
                onCancel={() => {
                  setLine(-1);
                  setDeleteVisible(false);
                }}
                okText="确认删除" 
                cancelText="再想想"
                placement="topRight"
                title="计划删除后将无法恢复，是否继续？">
                <a onClick={() => {
                  setDeleteVisible(true);
                  setLine(index);
                }}>删除</a>
              </Popconfirm>
            </PermissionControl>,
            <PermissionControl key="delete"  action_id="400401011">
              <a key="copy" onClick={() => {
                setAddProjectPlanDialog(true);
                setOptType(OptType.COPY);
                setCurrentRow({
                  frequency_id: record.frequency_id,
                  frequency_name: record.frequency_name,
                  frequency_desc: record.frequency_desc,
                  begin_time: record.begin_time,
                  end_time: record.end_time,
                  use_num: record.use_num,
                  is_first: record.is_first,
                  is_long: record.is_long
                });
              }}>复制</a>
            </PermissionControl>
          ];
        }

        // R：执行中
        if (plan_status === 'R') {
          return [
            <PermissionControl key="stop" action_id="400401009">
              <a onClick={() => {
                // setLine(index);
                setStopVisible(true);
                setCurrentRow(record);
              }}>停止</a>
              {/* <Popconfirm 
                visible={stopVisible && line === index}
                okButtonProps={{loading: stopLoading}}
                onConfirm={async () => {
                  setStopLoading(true);
                  const success = await modifyPlanProjectStatus({
                    order_id: newCreateOrderId,
                    project_id: record.project_id as string,
                    plan_status: 'S'
                  });
                  setStopLoading(false);
                  setStopVisible(false);
                  setLine(-1);
                  if (success) {
                    showMsg('计划已停止', MsgType.SUCCESS);
                    actionRef.current?.reload();
                    stopProject?.();
                  }
                }}
                onCancel={() => {
                  setStopVisible(false);
                  setLine(-1);
                }}
                okText="确认停止" 
                cancelText="再想想"
                title="提前停止计划将终止计费，是否继续？">
                <a onClick={() => {
                  setLine(index);
                  setStopVisible(true);
                }}>停止</a>
              </Popconfirm> */}
            </PermissionControl>,
            <a key="copy" onClick={() => {
              setAddProjectPlanDialog(true);
              setOptType(OptType.COPY);
              setCurrentRow({
                frequency_id: record.frequency_id,
                frequency_name: record.frequency_name,
                frequency_desc: record.frequency_desc,
                begin_time: record.begin_time,
                end_time: record.end_time,
                use_num: record.use_num,
                is_first: record.is_first,
                is_long: record.is_long
              });
            }}>复制</a>
          ];
        }
        
        return [];
      }
    }
  ];

  /**
   * 批量停止
   * @returns 
   */
  const onBatchStop = async (end_time) => {
    try {
      await batchStopPlanProject(order_id as string, selectIds, end_time);
      showMsg('计划已停止', MsgType.SUCCESS);
      setSelectIds([]);
      setSelectRows([]);
      setStopVisible(false);
      actionRef.current?.clearSelected?.();
      actionRef.current?.reload();
      stopProject?.();
    } catch (error) {
      showMsg(error?.data?.errmsg);
    }
  }

  /**
   * 更新计划项目状态
   * @param params 
   * @returns 
   */
  const modifyPlanProjectStatus = async (params: {
    order_id: string;
    project_id: string;
    plan_status: string;
    begin_time?: string;
    end_time?: string;
  }) => {
    try {
      await updatePlanProjectStatus(params);
      return true;
    } catch (error) {
      showMsg(error?.data?.errmsg);
      return false;
    }
  }

  /**
   * 添加/修改项目计划
   */
  const handleAdd = async (fields: any) => {
    try {
      console.log(fields);
      if (optType === OptType.ADD || optType === OptType.COPY) {
        await addPlanProject(fields);
      } else {
        await updatePlanProject(fields);
      }
      setNewCreateOrderId(fields.order_id);
      actionRef.current?.reload();
      return true;
    } catch (error) {
      showMsg(error?.data?.errmsg);
      return false;
    }
  }

  useImperativeHandle(ref, () => ({
    reload: () => actionRef.current?.reload(),
    clear: () => {
      setNewCreateOrderId('');
      actionRef.current?.reload();
    },
  }))

  useEffect(() => {
    if (order_id) {
      actionRef.current?.reload();
    }
    setNewCreateOrderId(order_id);
  }, [order_id]);

  const range = (start, end) => {
    const result = [];
    for (let i = start; i < end; i++) {
      result.push(i);
    }
    return result;
  }

  // 判断停止时间大小
  const checkStopTime = (current) => {
    const beginTime = moment(currentRow.begin_time);
    const endTime = moment(currentRow.end_time);
    const c = moment(current).format('YYYY-MM-DD HH:mm:ss'); // 所选时间
    const b = moment(beginTime).format('YYYY-MM-DD HH:mm:ss') // 开始时间
    const e = moment(endTime).format('YYYY-MM-DD HH:mm:ss') // 结束时间
    if (!moment(current).isAfter(beginTime) || c === b) {
      message.error(`停止时间不能小于${currentRow.begin_time}`)
      return false
    }
    // if (moment(current).isAfter(moment(currentRow.end_time)) && c !== e) {
    //   message.error(`停止时间不能大于${currentRow.end_time}`);
    //   return false
    // }
    return true;
  }

  return <div className="service-record">
     <div className="header">
        <div className="title">2. 项目计划 </div>
        <div className="btns fwb">
          责任人：{initialState?.currentUser?.oper_name}
        </div>
      </div>
      <Divider style={{margin: '10px 0 0'}} />
      <ProTable<ProjectPlanItem, COMMON.PageParams & { order_id: string;}>
        rowKey="project_id"
        actionRef={actionRef}
        options={false}
        rowSelection={{
          columnWidth: 30,
          getCheckboxProps: (record: ProjectPlanItem) => ({
            disabled: record.plan_status !== 'R'
          }),
          onChange: (selectedRowKeys: React.Key[], selRows: ProjectPlanItem[]) => {
            if (!selRows.length) {
              setSelectIds([]);
              setSelectRows([]);
              return
            }
            const rows = selRows.map(item => {
              return item.project_id;
            });
            setSelectIds(rows as string[]);
            const ary = selRows.sort((a, b) => b.begin_time.localeCompare(a.begin_time) || b.begin_time.localeCompare(a.begin_time));
            console.log('ary', ary);
            setSelectRows(ary);
          }
        }}
        request={async (params) => {
          if (!newCreateOrderId) {
            return {
              data: [],
              total: 0,
              success: true
            }
          }
          try {
            params = Object.assign({}, params, { order_id: newCreateOrderId as string });
            const data: ProjectPlanItemList = await getPlanProjectList(params);
            return {
              data: data.record_list,
              total: data.sum_record_num,
              success: true
            }
          } catch (error) {
            showMsg(error?.data?.errmsg);
            return {
              data: [],
              total: 0,
              success: true
            }
          }
        }}
        bordered
        search={false}
        pagination={{
          showQuickJumper: true
        }}
        toolbar={{
          menu: {
            type: 'inline',
            items: [
              {
                key: 'add',
                label: <PermissionControl action_id="400401006">
                  <Button 
                    onClick={() => {
                      setCurrentRow({});
                      setAddProjectPlanDialog(true);
                      setOptType(OptType.ADD);
                    }} 
                    disabled={['F'].includes(detail.plan_status) || 
                    !order_id && !patientHospitalInfo?.patient_id || 
                    ['W', 'F'].includes(dischargeStatus as string)}
                    icon={<PlusOutlined />}
                    type="primary">
                    添加
                  </Button>
                </PermissionControl>
              },
              {
                key: 'batchstop',
                label: <PermissionControl action_id="400401007">
                    <Button 
                      disabled={!selectIds.length}
                      onClick={() => {
                        // onBatchStop();
                        setStopVisible(true);
                      }} 
                      icon={ <PauseCircleOutlined /> }
                      type="primary">
                      批量停止
                    </Button>
                </PermissionControl>
              }
            ]
          }
        }}
        scroll={{ x : isScroll ? 1200 : null }}
        columns={columns}
        onRow={record => {
          return {
            onClick: event => { setClickRow(record.project_id) }, // 点击行
            onMouseEnter: event => {}, // 鼠标移入行
            onMouseLeave: event => {},
          };
        }}
        rowClassName={(record) => {
          return record.project_id === clickRow ? 'tableRowClick' : ''
        }}
      />

      {
        addProjectPlanDialog && <AddProjectPlan 
          handleModalVisible={setAddProjectPlanDialog} 
          handleAdd={handleAdd}
          patientHospitalInfo={patientHospitalInfo}
          record={currentRow}
          actionRef={actionRef}
          order_id={newCreateOrderId}
          optType={optType}
        />
      }
      {
        stopVisible &&
        <ModalForm
          title={`请选择所选${selectRows.length > 0 ? `${selectRows.length}个` : ''}计划停止时间`}
          width="30%"
          visible
          modalProps={{
            maskClosable: false
          }}
          layout="horizontal"
          className="modal-form"
          formRef={formRef}
          onVisibleChange={setStopVisible}
          onFinish={async (values) => {
            // console.log(values, moment(values.end_time).format('YYYYMMDDHHmmss'));
            // return;
            // if (!checkStopTime(values.end_time)) {
            //   return;
            // }
            const end = moment(values.end_time).format('YYYYMMDDHHmmss');
            if (selectRows.length > 0) {
              onBatchStop(end);
            } else {
              setStopLoading(true);
              const success = await modifyPlanProjectStatus({
                order_id: newCreateOrderId,
                project_id: currentRow.project_id as string,
                plan_status: 'S',
                end_time: end
              });
              setStopLoading(false);
              setStopVisible(false);
              setLine(-1);
              if (success) {
                showMsg('计划已停止', MsgType.SUCCESS);
                actionRef.current?.reload();
                stopProject?.();
              }
            }
          }}
          submitter={{
            searchConfig: {
              resetText: '再想想',
              submitText: '确认停止'
            },
            submitButtonProps: {
              // loading: loading
            }
          }}>
          <ProFormDateTimePicker
            rules={[
              {
                required: true
              }
            ]}
            label="结束时间"
            width="sm"
            name="end_time"
            fieldProps={{
              // showTime: { defaultValue: moment('23:59:59', 'HH:mm:ss')},
              onChange: () => {
                // calcPredictFee()
                console.log('onchange')
              },
              onOk: (current) => {
                // checkStopTime(current)
              },
              disabledDate: (current) => {
                // let begin = moment(currentRow.begin_time);
                // const hour = parseInt(begin.format('HH'), 10);
                // const minite = parseInt(begin.format('mm'), 10);
                // const second = parseInt(begin.format('ss'), 10);
                // if (hour === 23 && minite === 59 && second === 59) { // 23:59:59,就跨日
                //   begin = moment(begin).add(1, 'days');
                // }
                // return current && (moment(current).endOf('day') < moment(begin).endOf('day') || current >= moment().add(1, 'days').set({ hour: 0, minute: 0, second: 0  }))
                return current && (moment(current).endOf('day') < moment().endOf('day') || current >= moment().add(1, 'days').set({ hour: 0, minute: 0, second: 0  }))
              },
              // disabledTime: (current) => {
              //   const cur = moment(current).endOf('day').format('YYYY-MM-DD');
              //   // const today = moment().endOf('day').format('YYYY-MM-DD');
              //   // // 如果选中为今天，默认为当前时间
              //   // if (cur === today) {
              //   //   return true
              //   // }
              //   const beginTime = currentRow.begin_time;
              //   // const beginTime = moment('2021-11-02 23:59:59');
              //   const begin = beginTime.format('YYYY-MM-DD');
              //   // const begin = moment(currentRow.begin_time).endOf('day').format('YYYY-MM-DD');
              //   // console.log('disa', moment(cur).format('YYYY-MM-DD'), moment(begin).format('YYYY-MM-DD'))
              //   // console.log('range(0, 24)', range(0, 24), range(0, 24).splice(4, 20))

              //   // 如果选中日期为计划开始时间
              //   if (cur === begin) {
              //     let hour = parseInt(beginTime.format('HH'), 10);
              //     let minite = parseInt(beginTime.format('mm'), 10);
              //     let second = parseInt(beginTime.format('ss'), 10);

              //     const curHour = parseInt(moment(current).format('HH'), 10);
              //     console.log('hour', moment(beginTime).format('HH:mm:ss'), hour, minite, second, 111, (minite === 59 && second === 59));
              //     console.log('curHour', curHour);
              //     if (curHour > hour) {
              //       // hour ;
              //       minite = 0;
              //       second = 0;
              //     } else {
              //       if (minite === 59 && second === 59) {
              //         hour += 1;
              //         minite = 0;
              //         second = 0;
              //       } else if (second === 59) {
              //         minite += 1;
              //         second = 0;
              //       } else {
              //         second += 1;
              //       }
              //     }
              //     return {
              //       disabledHours: () => range(0, 24).splice(0, hour),
              //       disabledMinutes: () => range(0, minite),
              //       disabledSeconds: () => range(0, 60).splice(0, second) //[0, second],
              //     };
              //   }
              // },
              // showTime: { defaultValue: moment(new Date(), 'HH:mm:ss') },
              // renderExtraFooter: () => <span className='red' style={{ fontSize: 12 }}>{selectRows.length > 0 ? `停止时间不能大于：${currentRow.end_time}` : `原计划开始时间：${currentRow.begin_time}，结束时间：${currentRow.end_time}`}</span>,
              renderExtraFooter: () => <span className='red' style={{ fontSize: 12 }}>{selectRows.length > 0 ? `停止时间最晚为今日23:59:59` : `原计划开始时间：${currentRow.begin_time}，停止时间最晚为今日23:59:59`}</span>,
            }}
            initialValue={moment()}
          />
          {/* <div className='red'>提前停止计划将终止计费</div> */}
          <div className="modal-tips">
            <ExclamationCircleOutlined />
            <span>提前停止计划将终止计费</span>
          </div>
        </ModalForm>
      }
  </div>
});
export default ProjectPlan;